package com.example.sentinel.common.config;

import com.example.sentinel.common.bean.ErrorException;
import com.example.sentinel.common.bean.FailException;
import com.example.sentinel.common.bean.Result;
import com.example.sentinel.common.bean.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义全局异常处理
 *
 * @author luojm
 * 2019-11-22 15:24:58
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(FailException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result baseExceptionHandler(FailException e) {
        log.info(e.getMessage());
        return Result.fail(e.getMessage()).code(ResultCode.FAIL.getCode());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result baseExceptionHandler(IllegalArgumentException e) {
        log.info(e.getMessage());
        return Result.fail(e.getMessage()).code(ResultCode.PARAMERROR.getCode());
    }

    @ExceptionHandler(ErrorException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result errorException(IllegalArgumentException e) {
        log.info(e.getMessage());
        return Result.fail(e.getMessage()).code(ResultCode.SERVICEERROR.getCode());
    }

    /**
     * 全局异常.
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleGlobalException(Exception e) {
//        Tracer.trace(e);
        Throwable cause = e.getCause();
        do {
            cause = cause.getCause();
        } while (null != cause.getCause());

        if (cause instanceof FailException) {
            log.error("业务处理失败 FailException={}", e.getMessage(), e);
            return Result.fail(cause.getMessage()).code(ResultCode.FAIL.getCode());
        } else if (cause instanceof IllegalArgumentException) {
            log.error("参数错误 IllegalArgumentException={}", e.getMessage(), e);
            return Result.fail(cause.getMessage()).code(ResultCode.PARAMERROR.getCode());
        } else {
            log.error("全局异常信息 exception={}", e.getMessage(), e);
            return Result.fail(cause.getMessage()).code(ResultCode.SERVICEERROR.getCode());
        }
    }
}
